﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TopVidionApplication;
using TopVisionLog;
using TopVisionVideoStream;
using VideoStream.Common;
using VideoStream.Model;
using System.Linq;

namespace VideoStream.Windows
{
    public partial class Windows_Login : VideoStream.Windows.WindowsBase
    {
        private string code;
        private string accountInput;
        private string passwordInput;
        private string codeInput;
        private bool logging = false;
        private int loginDelay = 1000;
        private Image errImg;

        private Windows_MessageBox messagebox;

        public Windows_Login()
        {
            InitializeComponent();
            InitUI();
            this.Tag = "winLogin";
        }


        #region Override

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            InitEvent();
            UpdateUI();
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            Windows_Main.Instance.ShowMask(false);
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            HttpAPI.DownloadDataCompleted -= HttpAPI_DownloadDataCompleted;
        }

        public override void InitUI()
        {
            base.InitUI();
            this.TopLevel = false;
            this.Dock = DockStyle.Fill;
        }

        public override void InitEvent()
        {
            base.InitEvent();

            // Code
            pic_Code.Click += Pic_Code_Click;

            // Button
            btn_Login.Click += Btn_Login_Click;
            llab_ForgetPassword.Click += Llab_ForgetPassword_Click;

            // Text
            txt_AccountInput.KeyPress += Txt_Input_KeyPress;
            txt_PasswordInput.KeyPress += Txt_Input_KeyPress;
            txt_CodeInput.KeyPress += Txt_Input_KeyPress;
            txt_PasswordInput.TextChanged += Txt_PasswordInput_TextChanged;

            // Httpapi
            HttpAPI.DownloadDataCompleted += HttpAPI_DownloadDataCompleted;
        }

        private void Txt_Input_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                Login();
                e.Handled = true;
            }
        }

        public override void UpdateUI()
        {
            base.UpdateUI();

            // Code
            UpdateCode();

            lab_Msg.Text = TVString.STR_LoginTitle;
            lab_Msg.Font = TVFont.DefaultFont16;
            lab_Notify.Text = "";

            HideNotify();
#if DEBUG
            //txt_AccountInput.Text = "3186018";
            //txt_PasswordInput.Text = "123456";
#endif

            if (ApplicationData.KeepPassword)
            {
                txt_AccountInput.Text = ApplicationData.Account;
                txt_PasswordInput.Text = ApplicationData.Password;
            }
            else
            {
                txt_AccountInput.Text = ApplicationData.Account;
            }
            cb_SavePassword.Checked = ApplicationData.KeepPassword;
        }

        #endregion


        #region Control Event

        private void Btn_Login_Click(object sender, EventArgs e)
        {
            Login();
        }

        private void Pic_Code_Click(object sender, EventArgs e)
        {
            UpdateCode();
        }

        private void Llab_ForgetPassword_Click(object sender, EventArgs e)
        {
            ForgetPassword();
        }

        private void Txt_PasswordInput_TextChanged(object sender, EventArgs e)
        {
            cb_SavePassword.Checked = false;
        }

        #endregion


        #region TVVS Event

        private async void LoginResult(bool isScucess, int msg)
        {
            if (isScucess)
            {
                ApplicationData.Account = accountInput;
                ApplicationData.Password = passwordInput;
                ApplicationData.KeepPassword = cb_SavePassword.Checked;
                HttpAPI.ResolutionLimit(TVVS.CompanyID);
                this.Hide();
                if (ApplicationData.KeepPassword)
                {
                    CommonFun.SaveUesrInfo(ApplicationData.Account, ApplicationData.Password);
                }
                ////CommonFun.Netchecking(null, 1000);
                //await Task.Delay(1000);
                Windows_Main.Instance.IsLogin = true;
            }
            else
            {
                CommonFun.SaveUesrInfo(accountInput, "");
                ShowNotify(TVString.STR_InvalidAccount, Color.Red, true);
                SetLoginActive(true);
                logging = false;
            }
        }

        private void HttpAPI_DownloadDataCompleted(object sender, System.Net.DownloadDataCompletedEventArgs e)
        {
            try
            {
                string json = Encoding.UTF8.GetString(e.Result);
                TVHttpResult result = JsonConvert.DeserializeObject<TVHttpResult>(json);
                if (result.companyPro == null)
                {
                    ApplicationData._CompanyPro = new CompanyPro() { resolution = "1080" };
                }
                else
                {
                    ApplicationData._CompanyPro = result.companyPro;
                }
            }
            catch (Exception ex)
            {
                ApplicationData._CompanyPro = new CompanyPro() { resolution = "240" };
                TVLog.WriteLine("error : get Resolution limit " + ex.Message);
                Console.WriteLine("error : get Resolution limit " + ex.Message);
            }
            Windows_Main.Instance.ShowVideoCallWindows();
            this.Close();
        }

        #endregion


        #region Method

        private void UpdateCode()
        {
            code = CommonFun.CheckCode();
            CommonFun.CodeImage(code, pic_Code);
            code = code.Replace(" ", "").ToLower();

#if DEBUG
            txt_CodeInput.Text = "";
            txt_CodeInput.Text = code;
#endif
        }

        /// <summary>
        /// 用户输入内容空检测
        /// </summary>
        /// <returns></returns>
        private int CheckUserInput()
        {
            int err = 0;

            string _accountInput = txt_AccountInput.Text.Trim();
            string _passwordInput = txt_PasswordInput.Text.Trim();
            string _codeInput = txt_CodeInput.Text.Trim().ToLower();

            if (string.IsNullOrEmpty(_accountInput))
            {
                err = 1;
            }
            else if (string.IsNullOrEmpty(_passwordInput))
            {
                err = 2;
            }
            else if ((string.IsNullOrEmpty(_codeInput) & _codeInput.Length != 4) || _codeInput != code)
            {
                err = 3;
            }
            else
            {
                accountInput = _accountInput;
                passwordInput = _passwordInput;
                codeInput = _codeInput;
            }

            return err;
        }

        private void ShowNotify(string msg, Color color, bool err = false)
        {
            lab_Notify.Text = msg;
            lab_Notify.ForeColor = color;
            if (err)
            {
                lab_Notify.Image = errImg;
            }
            else
            {
                if (lab_Notify.Image != null)
                    errImg = lab_Notify.Image;
                lab_Notify.Image = null;
            }
            lab_Notify.Show();
        }

        private void HideNotify()
        {
            errImg = lab_Notify?.Image;
            lab_Notify.Hide();
        }

        private void SetLoginActive(bool active)
        {
            panel_Login.Enabled = active;
        }

        private async void Login()
        {
            if (logging) return;
            logging = true;
            var err = CheckUserInput();
            if (err == 0)
            {
                SetLoginActive(false);
                ShowNotify(TVString.STR_Logining, Color.Black);
                await Task.Delay(loginDelay);
                TVVS.Login(accountInput, passwordInput, LoginResult);
            }
            else
            {
                if (err == 1)
                {
                    ShowNotify(string.Format(TVString.STR_F_IsEmpry, TVString.STR_Account), Color.Red, true);
                    txt_AccountInput.Focus();
                }
                else if (err == 2)
                {
                    ShowNotify(string.Format(TVString.STR_F_IsEmpry, TVString.STR_Password), Color.Red, true);
                    txt_PasswordInput.Focus();
                }
                else if (err == 3)
                {
                    ShowNotify(TVString.STR_ErrorCode, Color.Red, true);
                    txt_CodeInput.Focus();
                }

                logging = false;
                CommonFun.SaveUesrInfo(accountInput, "");
            }

            if (!cb_SavePassword.Checked)
            {
                CommonFun.SaveUesrInfo(accountInput, "");
            }
        }

        private void ForgetPassword()
        {
            messagebox = new Windows_MessageBox(TVString.STR_ContactTheAdministrator, MessageBoxButtons.OK, MessageBoxIcon.Information);
            messagebox.Width = 300;
            messagebox.ShowDialog(this);
        }

        #endregion


        #region Helper


        #endregion

    }
}
